(function ($) {
    var KEY_PAGE_INDEX_INPUT = "_jpager-index-input";
    var KEY_PAGE_SIZE_INPUT = "_jpager-size-input";
    var OPTION = {
        //最多显示多少页码（目前仅支持偶数）
        maxPage: 6,
        //默认每页数据量
        defaultSize: 12,
        defaultTotal: 100,
        disabledClass: "disabled",
        helpClass: "help",
        selector: {
            edged: {
                searchForm: "form.lookup",
                totalDisplay: ".total",
                pageNumber: "em"
            }, bootstrap: {
                searchForm: "form.lookup",
                totalDisplay: ".total",
                pageNumber: "span"
            }
        },
        name: {
            currentPage: "page",
            pageSize: "size"
        },
        style: "bootstrap",
        template: {
            edged: {
                $firstPage: $('<a href="javascript:;" class="firstPage eTxt button"><em>首页</em></a>'),
                $lastPage: $('<a href="javascript:;" class="lastPage eTxt button"><em>末页</em></a>'),
                $prevPage: $('<a href="javascript:;" class="prevPage eTxt button"><em>前一页</em></a>'),
                $nextPage: $('<a href="javascript:;" class="nextPage eTxt button"><em>下一页</em></a>'),
                $page: $('<a href="javascript:;" class="page eTxt button"><em>#</em></a>'),
                $currentPage: $('<a href="javascript:;" class="currentPage eDq button"><em>#</em></a>'),
                $input: $('<input type="hidden"/>')
            },
            bootstrap: {
                $firstPage: $('<li class="first PagingFork"><span>首页</span></li>'),
                $lastPage: $('<li class="last"><span>末页</span></li>'),
                $prevPage: $('<li class="prev"><span>前一页</span></li>'),
                $nextPage: $('<li class="next"><span>下一页</span></li>'),
                $page: $('<li class="page"><span>#</span></li>'),
                $currentPage: $('<li class="active"><span>#</span></li>'),
                $input: $('<input type="hidden"/>')
            }
        },
        //当前页码.
        page: function ($dom) {
            return $dom.data("page");
        },
        //每页的数据量
        size: function ($dom) {
            return $dom.data("size");
        },
        //总数据量. 用于计算一共多少页。
        total: function ($dom) {
            return $dom.data("total");
        }
    };

    jQuery.fn.extend({
        "pager": function (option) {
            if ($.isWindow(this)) {
                return this;
            }
            var $this = this;
            var opt = $.extend(true, OPTION, $this.data(), option);
            var template = opt.template[opt.style];
            var selector = opt.selector[opt.style];
            var $pagerForm = $this.parents("form");
            var _cacheKey = "_jpager-page";
            var calcData = function () {
                //每页显示多少条数据
                var pageSize = opt.size || opt.defaultSize;
                if ($.isFunction(pageSize)) {
                    pageSize = pageSize($this) || opt.defaultSize;
                }
                //共有多少条数据
                var totalSize = opt.total !== undefined && opt.total >= 0 ? opt.total : opt.defaultTotal;
                if ($.isFunction(totalSize)) {
                    totalSize = totalSize($this) || opt.defaultTotal;
                }
                //当前要显示第几页  ※
                var currentPage = opt.page || 1;
                if ($.isFunction(currentPage)) {
                    currentPage = currentPage($this) || 1;
                }
                var pager = {
                    page: currentPage,
                    size: pageSize,
                    total: totalSize
                };
                return pager;
            };
            var calcIndex = function (pager) {
                //一共有多少页      ※
                var totalPage = Math.ceil((pager.total || 1) / pager.size);
                //从第几页开始显示链接
                var displayStart;
                //最多显示到第几页
                var displayEnd;
                //---------------------计算要显示的页码开始-----------------------
                var halfMaxDisplay = Math.ceil(opt.maxPage / 2);
                if (totalPage < opt.maxPage) {
                    displayStart = 1;
                    displayEnd = totalPage;
                } else if (totalPage >= opt.maxPage && pager.page < halfMaxDisplay) {
                    displayStart = 1;
                    displayEnd = opt.maxPage;
                } else if (totalPage >= opt.maxPage && pager.page >= totalPage - halfMaxDisplay) {
                    displayStart = totalPage - opt.maxPage + 1;
                    displayEnd = totalPage;
                } else {
                    displayStart = pager.page - halfMaxDisplay + 1;
                    displayEnd = pager.page + halfMaxDisplay;
                }
                var index = {
                    start: displayStart,
                    end: displayEnd,
                    total: totalPage
                };
                return index;
            };
            var pageClick = function () {
                var $page = $(this);
                var $currentPage = $("[name=" + opt.name.currentPage + "]", $pagerForm);
                if ($currentPage.length === 0) {
                    $currentPage = template.$input.clone();
                    $currentPage.attr("name", opt.name.currentPage);
                    $pagerForm.append($currentPage);
                }
                $currentPage.val($page.data(_cacheKey));
                $pagerForm.submit();
            };
            $pagerForm.submit(function () {
                var $this = $(this);
                var $searchForm = $(selector.searchForm);
                if ($searchForm.length === 0) {
                    return true;
                }
                var $lookups = $(":text,input[type=datetime],input:hidden", $searchForm).clone().removeAttr("id");
                _cloneOtherInput($searchForm, $this);
                $this.append($lookups);
                this.submit();
                $lookups.remove();
                _removeOtherInput($this);
                return false;

                function _cloneOtherInput($searchForm, $pagerForm) {
                    var $select = $("select", $searchForm);
                    $select.each(function (i, select) {
                        var value = $(select).val();
                        var $help = template.$input.clone();
                        $help.attr("name", select.name)
                            .addClass(opt.helpClass)
                            .val(value);
                        $pagerForm.append($help);
                    });
                }

                function _removeOtherInput($pagerForm) {
                    $("." + opt.helpClass, $pagerForm).remove();
                }
            });

            var pager = calcData();
            var index = calcIndex(pager);
            //<editor-fold defaultstate="collapsed" desc="处理首页">

            var $first = template.$firstPage.clone();
            if (pager.page === 1) {
                $first.addClass(opt.disabledClass);
            } else {
                $first.data(_cacheKey, 1).click(pageClick);
            }
            $this.append($first);
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理上一页">

            var $prev = template.$prevPage.clone();
            if (pager.page === 1) {
                $prev.addClass(opt.disabledClass);
            } else {
                $prev.data(_cacheKey, pager.page - 1).click(pageClick);
            }
            $this.append($prev);
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理具体页码">

            for (var i = index.start; i <= index.end; i++) {
                var $pageLink;
                if (i === pager.page) {
                    $pageLink = template.$currentPage.clone();
                    $pageLink.find(selector.pageNumber).text(i);
                    $this.append($pageLink);
                } else {
                    $pageLink = template.$page.clone();
                    $pageLink.find(selector.pageNumber).text(i);
                    $pageLink.data(_cacheKey, i).click(pageClick);
                    $this.append($pageLink);
                }
            }
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理下一页">

            var $next = template.$nextPage.clone();
            if (pager.page === index.total) {
                $next.addClass(opt.disabledClass);
            } else {
                $next.data(_cacheKey, pager.page + 1).click(pageClick);
            }
            $this.append($next);
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理末页">
            var $last = template.$lastPage.clone();
            if (pager.page === index.total) {
                $last.addClass(opt.disabledClass);
            } else {
                $last.data(_cacheKey, index.total).click(pageClick);
            }
            $this.append($last);
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理页码输入">
            var $currentPage = $("[name=" + opt.name.currentPage + "]", $pagerForm);
            if ($currentPage.length !== 0) {
                $this.data(KEY_PAGE_INDEX_INPUT, $currentPage);
                $currentPage.val(pager.page).change(function () {
                    var $this = $(this);
                    var forwardPage = Math.abs(Math.floor($this.val()));
                    $this.val(forwardPage);
                });
            }
            //</editor-fold>
            //<editor-fold defaultstate="collapsed" desc="处理页大小选择">
            var pageSize = $("[name=" + opt.name.pageSize + "]", $pagerForm);
            if (pageSize.length !== 0) {
                $this.data(KEY_PAGE_SIZE_INPUT, pageSize);
                pageSize.val(pager.size);
                pageSize.change(function () {
                    $currentPage.val(1);
                    $pagerForm.submit();
                });
            }
            //</editor-fold>

            //处理总数量显示
            $(selector.totalDisplay, $pagerForm).text(pager.total);
            return $this;
        }
    });


    function _replaceMetacharator(metastring) {
        return metastring.replace(/[.]/, "\\.");
    }
})(jQuery);